<!DOCTYPE html>
<html lang="en">
  <head>
    <title>
        Java-framework-MyBatis-2-关联查询 - rulerLwx Blog
      </title>
        <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport"
      content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no, minimal-ui">
    <meta name="renderer" content="webkit">
    <meta http-equiv="Cache-Control" content="no-transform" />
    <meta http-equiv="Cache-Control" content="no-siteapp" />
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <meta name="format-detection" content="telephone=no,email=no,adress=no">
    
    <meta name="theme-color" content="#000000" />
    
    <meta http-equiv="window-target" content="_top" />
    
    
    <meta name="description" content="关联查询 商品订单数据模型 一对一查询 案例：查询所有订单信息，关联查询下单用户信息。 注意：因为一个订单信息只会是一个人下的订单，所以从查询订单信" />
    <meta name="generator" content="Hugo 0.73.0 with theme pure" />
    <title>Java-framework-MyBatis-2-关联查询 - rulerLwx Blog</title>
    
    
    <link rel="stylesheet" href="https://rulerLwx.gitee.io/css/style.min.c4bc7071f132c964c2116bca53b392933f377e5ca7b7051ed245187c621a2d3e.css">
    
    <link rel="stylesheet" href="https://cdn.staticfile.org/highlight.js/9.15.10/styles/github.min.css" async>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/tocbot/4.4.2/tocbot.css" async>
    <meta property="og:title" content="Java-framework-MyBatis-2-关联查询" />
<meta property="og:description" content="关联查询 商品订单数据模型 一对一查询 案例：查询所有订单信息，关联查询下单用户信息。 注意：因为一个订单信息只会是一个人下的订单，所以从查询订单信" />
<meta property="og:type" content="article" />
<meta property="og:url" content="https://rulerLwx.gitee.io/2020/07/java-framework-mybatis-2-%E5%85%B3%E8%81%94%E6%9F%A5%E8%AF%A2/" />
<meta property="article:published_time" content="2020-07-01T18:58:47+08:00" />
<meta property="article:modified_time" content="2020-07-01T18:58:47+08:00" />
<meta itemprop="name" content="Java-framework-MyBatis-2-关联查询">
<meta itemprop="description" content="关联查询 商品订单数据模型 一对一查询 案例：查询所有订单信息，关联查询下单用户信息。 注意：因为一个订单信息只会是一个人下的订单，所以从查询订单信">
<meta itemprop="datePublished" content="2020-07-01T18:58:47&#43;08:00" />
<meta itemprop="dateModified" content="2020-07-01T18:58:47&#43;08:00" />
<meta itemprop="wordCount" content="2744">



<meta itemprop="keywords" content="" /><meta name="twitter:card" content="summary"/>
<meta name="twitter:title" content="Java-framework-MyBatis-2-关联查询"/>
<meta name="twitter:description" content="关联查询 商品订单数据模型 一对一查询 案例：查询所有订单信息，关联查询下单用户信息。 注意：因为一个订单信息只会是一个人下的订单，所以从查询订单信"/>

    <!--[if lte IE 9]>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/classlist/1.1.20170427/classList.min.js"></script>
      <![endif]-->

    <!--[if lt IE 9]>
        <script src="https://cdn.jsdelivr.net/npm/html5shiv@3.7.3/dist/html5shiv.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/respond.js@1.4.2/dest/respond.min.js"></script>
      <![endif]-->
  </head>

  
  

  <body class="main-center theme-black" itemscope itemtype="http://schema.org/WebPage"><header class="header" itemscope itemtype="http://schema.org/WPHeader">
    <div class="slimContent">
      <div class="navbar-header">
        <div class="profile-block text-center">
          <a id="avatar" href="https://gitee.com/rulerLwx" target="_blank">
            <img class="img-circle img-rotate" src="https://rulerLwx.gitee.io/avatar.png" width="200" height="200">
          </a>
          <h2 id="name" class="hidden-xs hidden-sm">rulerLwx</h2>
          <h3 id="title" class="hidden-xs hidden-sm hidden-md">thinking...</h3>
          <small id="location" class="text-muted hidden-xs hidden-sm"><i class="icon icon-map-marker"></i>Guangzhou, China</small>
        </div><div class="search" id="search-form-wrap">
    <form class="search-form sidebar-form">
        <div class="input-group">
            <input type="text" class="search-form-input form-control" placeholder="Search" />
            <span class="input-group-btn">
                <button type="submit" class="search-form-submit btn btn-flat" onclick="return false;"><i
                        class="icon icon-search"></i></button>
            </span>
        </div>
        <div class="ins-search">
            <div class="ins-search-mask"></div>
            <div class="ins-search-container">
                <div class="ins-input-wrapper">
                    <input type="text" class="ins-search-input" placeholder="Type something..."
                        x-webkit-speech />
                    <button type="button" class="close ins-close ins-selectable" data-dismiss="modal"
                        aria-label="Close"><span aria-hidden="true">×</span></button>
                </div>
                <div class="ins-section-wrapper">
                    <div class="ins-section-container"></div>
                </div>
            </div>
        </div>
    </form>
</div>
        <button class="navbar-toggle collapsed" type="button" data-toggle="collapse" data-target="#main-navbar" aria-controls="main-navbar" aria-expanded="false">
          <span class="sr-only">Toggle navigation</span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
        </button>
      </div>
      <nav id="main-navbar" class="collapse navbar-collapse" itemscope itemtype="http://schema.org/SiteNavigationElement" role="navigation">
        <ul class="nav navbar-nav main-nav">
            <li class="menu-item menu-item-home">
                <a href="/">
                    <i class="icon icon-home-fill"></i>
                  <span class="menu-title">Home</span>
                </a>
            </li>
            <li class="menu-item menu-item-archives">
                <a href="/posts/">
                    <i class="icon icon-archives-fill"></i>
                  <span class="menu-title">Archives</span>
                </a>
            </li>
            <li class="menu-item menu-item-categories">
                <a href="/categories/">
                    <i class="icon icon-folder"></i>
                  <span class="menu-title">Categories</span>
                </a>
            </li>
            <li class="menu-item menu-item-tags">
                <a href="/tags/">
                    <i class="icon icon-tags"></i>
                  <span class="menu-title">Tags</span>
                </a>
            </li>
            <li class="menu-item menu-item-about">
                <a href="/about/">
                    <i class="icon icon-cup-fill"></i>
                  <span class="menu-title">About</span>
                </a>
            </li>
        </ul>
      </nav>
    </div>
  </header>

<aside class="sidebar" itemscope itemtype="http://schema.org/WPSideBar">
  <div class="slimContent">
    
      <div class="widget">
    <h3 class="widget-title">Board</h3>
    <div class="widget-body">
        <div id="board">
            <div class="content">enjoy~
            </div>
        </div>
    </div>
</div>

      <div class="widget">
    <h3 class="widget-title"> Categories</h3>
    <div class="widget-body">
        <ul class="category-list">
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/java-framework/" class="category-list-link">java-framework</a><span class="category-list-count">38</span></li>
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/java-front-end/" class="category-list-link">java-front-end</a><span class="category-list-count">11</span></li>
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/java-se/" class="category-list-link">java-se</a><span class="category-list-count">21</span></li>
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/java-senior/" class="category-list-link">java-senior</a><span class="category-list-count">4</span></li>
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/linux/" class="category-list-link">linux</a><span class="category-list-count">13</span></li>
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/tools/" class="category-list-link">tools</a><span class="category-list-count">1</span></li>
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/%E6%8A%80%E6%9C%AF%E6%9D%82%E7%83%A9/" class="category-list-link">技术杂烩</a><span class="category-list-count">4</span></li>
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/%E6%95%B0%E6%8D%AE%E5%BA%93/" class="category-list-link">数据库</a><span class="category-list-count">15</span></li>
        </ul>
    </div>
</div>
      <div class="widget">
    <h3 class="widget-title"> Tags</h3>
    <div class="widget-body">
        <ul class="tag-list">
            
            
            <li class="tag-list-item"><a href="https://rulerLwx.gitee.io/tags/jvm/" class="tag-list-link">jvm</a><span
                    class="tag-list-count">1</span></li>
            
            
            <li class="tag-list-item"><a href="https://rulerLwx.gitee.io/tags/%E5%A4%9A%E7%BA%BF%E7%A8%8B/" class="tag-list-link">多线程</a><span
                    class="tag-list-count">2</span></li>
            
            
            <li class="tag-list-item"><a href="https://rulerLwx.gitee.io/tags/%E7%BD%91%E7%BB%9C%E7%BC%96%E7%A8%8B/" class="tag-list-link">网络编程</a><span
                    class="tag-list-count">3</span></li>
            
        </ul>

    </div>
</div>
      
<div class="widget">
    <h3 class="widget-title">Recent Posts</h3>
    <div class="widget-body">
        <ul class="recent-post-list list-unstyled no-thumbnail">
            <li>
                <div class="item-inner">
                    <p class="item-title">
                        <a href="https://rulerLwx.gitee.io/2020/07/%E8%87%AA%E5%B7%B1%E5%8A%A8%E6%89%8B%E4%B8%80%E6%89%B9%E9%87%8F%E7%A7%BB%E5%8A%A8%E9%87%8D%E5%91%BD%E5%90%8D%E6%96%87%E4%BB%B6/" class="title">自己动手（一）——批量移动、重命名文件</a>
                    </p>
                    <p class="item-date">
                        <time datetime="2020-07-27 17:50:02 &#43;0800 CST" itemprop="datePublished">2020-07-27</time>
                    </p>
                </div>
            </li>
            <li>
                <div class="item-inner">
                    <p class="item-title">
                        <a href="https://rulerLwx.gitee.io/2020/07/%E5%85%B3%E4%BA%8Einteger%E7%9A%84-128~127%E7%BC%93%E5%AD%98/" class="title">关于Integer的 -128~127缓存</a>
                    </p>
                    <p class="item-date">
                        <time datetime="2020-07-11 16:56:21 &#43;0800 CST" itemprop="datePublished">2020-07-11</time>
                    </p>
                </div>
            </li>
            <li>
                <div class="item-inner">
                    <p class="item-title">
                        <a href="https://rulerLwx.gitee.io/2020/07/%E8%B7%A8%E5%9F%9F%E9%97%AE%E9%A2%98/" class="title">跨域问题</a>
                    </p>
                    <p class="item-date">
                        <time datetime="2020-07-08 22:41:12 &#43;0800 CST" itemprop="datePublished">2020-07-08</time>
                    </p>
                </div>
            </li>
            <li>
                <div class="item-inner">
                    <p class="item-title">
                        <a href="https://rulerLwx.gitee.io/2020/07/%E4%B8%AA%E4%BA%BA%E5%8D%9A%E5%AE%A2%E6%90%AD%E5%BB%BA/" class="title">个人博客搭建</a>
                    </p>
                    <p class="item-date">
                        <time datetime="2020-07-05 18:58:47 &#43;0800 CST" itemprop="datePublished">2020-07-05</time>
                    </p>
                </div>
            </li>
            <li>
                <div class="item-inner">
                    <p class="item-title">
                        <a href="https://rulerLwx.gitee.io/2020/07/centos/" class="title">CentOS-</a>
                    </p>
                    <p class="item-date">
                        <time datetime="2020-07-01 18:58:47 &#43;0800 CST" itemprop="datePublished">2020-07-01</time>
                    </p>
                </div>
            </li>
        </ul>
    </div>
</div>
  </div>
</aside>

    
    
<aside class="sidebar sidebar-toc collapse" id="collapseToc" itemscope itemtype="http://schema.org/WPSideBar">
  <div class="slimContent">
    <h4 class="toc-title">Catalogue</h4>
    <nav id="toc" class="js-toc toc">

    </nav>
  </div>
</aside>
<main class="main" role="main"><div class="content">
  <article id="-" class="article article-type-" itemscope
    itemtype="http://schema.org/BlogPosting">
    
    <div class="article-header">
      <h1 itemprop="name">
  <a
    class="article-title"
    href="/2020/07/java-framework-mybatis-2-%E5%85%B3%E8%81%94%E6%9F%A5%E8%AF%A2/"
    >Java-framework-MyBatis-2-关联查询</a
  >
</h1>

      <div class="article-meta">
        
<span class="article-date">
  <i class="icon icon-calendar-check"></i>&nbsp;
<a href="https://rulerLwx.gitee.io/2020/07/java-framework-mybatis-2-%E5%85%B3%E8%81%94%E6%9F%A5%E8%AF%A2/" class="article-date">
  <time datetime="2020-07-01 18:58:47 &#43;0800 CST" itemprop="datePublished">2020-07-01</time>
</a>
</span>
<span class="article-category">
  <i class="icon icon-folder"></i>&nbsp;
  <a class="article-category-link" href="/categories/java-framework/"> Java-framework </a>
</span>

        <span class="post-comment"><i class="icon icon-comment"></i>&nbsp;<a href="/2020/07/java-framework-mybatis-2-%E5%85%B3%E8%81%94%E6%9F%A5%E8%AF%A2/#comments"
            class="article-comment-link">Comments</a></span>
		<span class="post-wordcount hidden-xs" itemprop="wordCount">Word Count: 2744words</span>
		<span class="post-readcount hidden-xs" itemprop="timeRequired">Read Count: 6minutes </span>
      </div>
    </div>
    <div class="article-entry marked-body js-toc-content" itemprop="articleBody">
      <h1 id="关联查询">关联查询</h1>
<h2 id="商品订单数据模型">商品订单数据模型</h2>
<p><img src="https://gitee.com/rulerLwx/PicGo/raw/master/img/20200708080942.png" alt=""></p>
<h2 id="一对一查询">一对一查询</h2>
<p>案例：查询所有订单信息，关联查询下单用户信息。</p>
<p>注意：因为一个订单信息只会是一个人下的订单，所以从查询订单信息出发关联查询用户信息为一对一查询。如果从用户信息出发查询用户下的订单信息则为一对多查询，因为一个用户可以下多个订单。</p>
<h3 id="方法一使用resulttype">方法一：使用resultType</h3>
<p>sql语句：</p>
<pre><code class="language-sql">SELECT 
  orders.*,
  user.username,
  user.address
FROM
  orders,
  user 
WHERE orders.user_id = user.id
</code></pre>
<ul>
<li>
<p>定义po类</p>
<p>此po类中包括了订单信息和用户信息，包括上边sql查询出来的所有字段，</p>
<p>OrdersCustom类继承Orders类后OrdersCustom类包括了Orders类的所有字段，只需要定义用户的信息字段即可。</p>
</li>
</ul>
<pre><code class="language-java">    public class OrdersCustom extends Orders {
    
    	private String username;// 用户名称
    	private String address;// 用户地址
    
        //ommitted get/set...
</code></pre>
<ul>
<li>Mapper.xml</li>
</ul>
<pre><code class="language-xml">	&lt;select id=&quot;findOrdersList&quot; resultType=&quot;cn.itcast.mybatis.po.OrdersCustom&quot;&gt;
    	SELECT
    	orders.*,
    	user.username,
    	user.address
    	FROM
    	orders,	user
    	WHERE orders.user_id = user.id 
	&lt;/select&gt;
</code></pre>
<ul>
<li>Mapper接口</li>
</ul>
<pre><code class="language-java">    public List&lt;OrdersCustom&gt; findOrdersList() throws Exception;
</code></pre>
<ul>
<li>测试</li>
</ul>
<pre><code class="language-java">    Public void testfindOrdersList()throws Exception{
		//获取session
		SqlSession session = sqlSessionFactory.openSession();
		//获限mapper接口实例
		UserMapper userMapper = session.getMapper(UserMapper.class);
		//查询订单信息
		List&lt;OrdersCustom&gt; list = userMapper.findOrdersList();
		System.out.println(list);
		//关闭session
		session.close();
	}
</code></pre>
<p>定义专门的po类作为输出类型，其中定义了sql查询结果集所有的字段。此方法较为简单，企业中使用普遍</p>
<h3 id="方法二使用resultmap">方法二：使用resultMap</h3>
<p>sql语句</p>
<pre><code class="language-sql">    SELECT 
      orders.*,
      user.username,
      user.address
    FROM
      orders,
      user 
    WHERE orders.user_id = user.id
</code></pre>
<ul>
<li>
<p>定义po类</p>
<p>在Orders类中加入User属性，user属性中用于存储关联查询的用户信息，因为订单关联查询用户是一对一关系，所以这里使用单个User对象存储关联查询的用户信息。</p>
</li>
<li>
<p>Mapper.xml</p>
<p>这里resultMap指定userordermap</p>
</li>
</ul>
<pre><code class="language-xml">    &lt;select id=&quot;findOrdersListResultMap&quot; resultMap=&quot;userordermap&quot;&gt;
    	SELECT
    	orders.*,
    	user.username,
    	user.address
    	FROM
    	orders,	user
    	WHERE orders.user_id = user.id 
	&lt;/select&gt;
</code></pre>
<ul>
<li>
<p>定义resultMap</p>
<p>需要关联查询映射的是用户信息，使用association将用户信息映射到订单对象的用户属性中</p>
</li>
</ul>
<pre><code class="language-xml">    &lt;resultMap type=&quot;cn.itcast.mybatis.po.Orders&quot; id=&quot;userordermap&quot;&gt;
        &lt;!-- 这里的id，是mybatis在进行一对一查询时将user字段映射为user对象时要使用，必须写 --&gt;
        &lt;id property=&quot;id&quot; column=&quot;id&quot;/&gt;
        &lt;result property=&quot;user_id&quot; column=&quot;user_id&quot;/&gt;
        &lt;result property=&quot;number&quot; column=&quot;number&quot;/&gt;
        &lt;association property=&quot;user&quot; javaType=&quot;cn.itcast.mybatis.po.User&quot;&gt;
            &lt;!-- 这里的id为user的id，如果写上表示给user的id属性赋值 --&gt;
            &lt;id property=&quot;id&quot; column=&quot;user_id&quot;/&gt;
            &lt;result property=&quot;username&quot; column=&quot;username&quot;/&gt;
            &lt;result property=&quot;address&quot; column=&quot;address&quot;/&gt;
        &lt;/association&gt;
    &lt;/resultMap&gt;
</code></pre>
<pre><code>association：表示进行关联查询单条记录
property：表示关联查询的结果存储在cn.itcast.mybatis.po.Orders的user属性中
javaType：表示关联查询的结果类型
&lt;id property=&quot;id&quot; column=&quot;user_id&quot;/&gt;：查询结果的user_id列对应关联对象的id属性，这里是&lt;id /&gt;表示user_id是关联查询对象的唯一标识。
&lt;result property=&quot;username&quot; column=&quot;username&quot;/&gt;：查询结果的username列对应关联对象的username属性。
</code></pre>
<ul>
<li>Mapper接口</li>
</ul>
<pre><code class="language-java">    public List&lt;Orders&gt; findOrdersListResultMap() throws Exception;
</code></pre>
<ul>
<li>测试</li>
</ul>
<pre><code class="language-java">    Public void testfindOrdersListResultMap()throws Exception{
		//获取session
		SqlSession session = sqlSessionFactory.openSession();
		//获限mapper接口实例
		UserMapper userMapper = session.getMapper(UserMapper.class);
		//查询订单信息
		List&lt;Orders&gt; list = userMapper.findOrdersList2();
		System.out.println(list);
		//关闭session
		session.close();
	}
</code></pre>
<ul>
<li>
<p>总结</p>
<p>使用 association 完成关联查询，将关联查询信息映射到pojo对象中。</p>
</li>
</ul>
<h2 id="一对多查询">一对多查询</h2>
<p>案例：查询所有订单信息及订单下的订单明细信息。</p>
<p>订单信息与订单明细为一对多关系。</p>
<p>使用resultMap实现</p>
<p>sql语句</p>
<pre><code class="language-sql">    SELECT 
      orders.*,
      user.username,
      user.address,
      orderdetail.id orderdetail_id,
      orderdetail.items_id,
      orderdetail.items_num
    FROM
      orders,user,orderdetail
    
    WHERE orders.user_id = user.id 
    AND orders.id = orderdetail.orders_id
</code></pre>
<ul>
<li>
<p>定义po类</p>
<p>在Orders类中加入User属性。</p>
<p>在Orders类中加入List<!-- raw HTML omitted --> orderdetails属性</p>
</li>
<li>
<p>Mapper.xml</p>
</li>
</ul>
<pre><code class="language-xml">    &lt;select id=&quot;findOrdersDetailList&quot; resultMap=&quot;userorderdetailmap&quot;&gt;
    	SELECT
    	orders.*,
    	user.username,
    	user.address,
    	orderdetail.id orderdetail_id,
    	orderdetail.items_id,
    	orderdetail.items_num
    	FROM orders,user,orderdetail
    	WHERE orders.user_id = user.id
    	AND orders.id = orderdetail.orders_id
	&lt;/select&gt;
</code></pre>
<ul>
<li>定义resultMap</li>
</ul>
<pre><code class="language-xml">    &lt;resultMap type=&quot;cn.itcast.mybatis.po.Orders&quot; id=&quot;userorderdetailmap&quot;&gt;
        &lt;id property=&quot;id&quot;column=&quot;id&quot;/&gt;
        &lt;result property=&quot;user_id&quot; column=&quot;user_id&quot;/&gt;
        &lt;result property=&quot;number&quot; column=&quot;number&quot;/&gt;
        &lt;association property=&quot;user&quot; javaType=&quot;cn.itcast.mybatis.po.User&quot;&gt;
            &lt;id property=&quot;id&quot; column=&quot;user_id&quot;/&gt;
            &lt;result property=&quot;username&quot; column=&quot;username&quot;/&gt;
            &lt;result property=&quot;address&quot; column=&quot;address&quot;/&gt;
        &lt;/association&gt;
        &lt;collection property=&quot;orderdetails&quot; ofType=&quot;cn.itcast.mybatis.po.Orderdetail&quot;&gt;
        	&lt;id property=&quot;id&quot; column=&quot;orderdetail_id&quot;/&gt;
        	&lt;result property=&quot;items_id&quot; column=&quot;items_id&quot;/&gt;
        	&lt;result property=&quot;items_num&quot; column=&quot;items_num&quot;/&gt;
        &lt;/collection&gt;
    &lt;/resultMap&gt;
</code></pre>
<p>另一种写法：</p>
<pre><code class="language-xml">    &lt;!--使用 extends 属性，重用了上面一对一关联查询时定义好的 resultmap --&gt;
    &lt;resultMap type=&quot;cn.itcast.mybatis.po.Orders&quot; id=&quot;userorderdetailmap&quot; extends=&quot;userordermap&quot;&gt;
    &lt;collection property=&quot;orderdetails&quot; ofType=&quot;cn.itcast.mybatis.po.Orderdetail&quot;&gt;
    	&lt;id property=&quot;id&quot; column=&quot;orderdetail_id&quot;/&gt;
    	&lt;result property=&quot;items_id&quot; column=&quot;items_id&quot;/&gt;
    	&lt;result property=&quot;items_num&quot; column=&quot;items_num&quot;/&gt;
    &lt;/collection&gt;
    &lt;/resultMap&gt;
</code></pre>
<ul>
<li>Mapper接口</li>
</ul>
<pre><code class="language-java">    public List&lt;Orders&gt;findOrdersDetailList () throws Exception;
</code></pre>
<ul>
<li>测试</li>
</ul>
<pre><code class="language-java">    Public void testfindOrdersDetailList()throws Exception{
		//获取session
		SqlSession session = sqlSessionFactory.openSession();
		//获限mapper接口实例
		UserMapper userMapper = session.getMapper(UserMapper.class);
		//查询订单信息
		List&lt;Orders&gt; list = userMapper.findOrdersDetailList();
		System.out.println(list);
		//关闭session
		session.close();
	}
</code></pre>
<h2 id="多对多查询">多对多查询</h2>
<ul>
<li>
<p>需求</p>
<p>查询用户购买的商品信息</p>
</li>
</ul>
<p>sql</p>
<pre><code class="language-sql">    SELECT
    	orders.*, 
    	USER.username,
    	USER.address,
    	orderdetail.id orderdetail_id,
    	orderdetail.items_id,
    	orderdetail.items_num,
    	items.name items_name,
    	items.detail items_detail
    FROM
    	orders,
    	USER,
    	orderdetail,
    	items
    WHERE
    	orders.user_id = USER .id
    AND orders.id = orderdetail.orders_id
    AND orderdetail.items_id = items.id
</code></pre>
<ul>
<li>
<p>定义po</p>
<p>在User中添加List<!-- raw HTML omitted --> orders 属性，在Orders类中加入List<!-- raw HTML omitted --> orderdetails属性</p>
</li>
<li>
<p>resultMap</p>
<p>需要关联查询映射的信息是：订单、订单明细、商品信息</p>
<p>订单：一个用户对应多个订单，使用collection映射到用户对象的订单列表属性中</p>
<p>订单明细：一个订单对应多个明细，使用collection映射到订单对象中的明细属性中</p>
<p>商品信息：一个订单明细对应一个商品，使用association映射到订单明细对象的商品属性中。</p>
</li>
</ul>
<pre><code class="language-xml">	 &lt;resultMap type=&quot;cn.itcast.mybatis.po.User&quot; id=&quot;userOrderListResultMap&quot;&gt;
	 	&lt;id column=&quot;user_id&quot; property=&quot;id&quot;/&gt;
		&lt;result column=&quot;username&quot; property=&quot;username&quot;/&gt;
	 	&lt;collection property=&quot;orders&quot; ofType=&quot;cn.itcast.mybatis.po.Orders&quot;&gt;
	      &lt;id  column=&quot;id&quot; property=&quot;id&quot;/&gt;
	      &lt;result property=&quot;number&quot; column=&quot;number&quot;/&gt;
         	&lt;collection property=&quot;orderdetails&quot; ofType=&quot;cn.itcast.mybatis.po.Orderdetail&quot;&gt;
         	 	&lt;id  column=&quot;orderdetail_id&quot; property=&quot;id&quot;/&gt;
          		&lt;result property=&quot;ordersId&quot; column=&quot;id&quot;/&gt;
         		&lt;result property=&quot;itemsId&quot; column=&quot;items_id&quot;/&gt;
          		&lt;result property=&quot;itemsNum&quot; column=&quot;items_num&quot;/&gt;
          		&lt;association property=&quot;items&quot; javaType=&quot;cn.itcast.mybatis.po.Items&quot;&gt;
    	  			 &lt;id column=&quot;items_id&quot; property=&quot;id&quot;/&gt;
    	   			 &lt;result column=&quot;items_name&quot; property=&quot;name&quot;/&gt;
    	   			 &lt;result column=&quot;items_detail&quot; property=&quot;detail&quot;/&gt;
    			&lt;/association&gt;
       		&lt;/collection&gt;
	   &lt;/collection&gt;
	 &lt;/resultMap&gt;
</code></pre>
<h2 id="延迟加载">延迟加载</h2>
<p>需要查询关联信息时，使用mybatis延迟加载特性可有效的减少数据库压力，首次查询只查询主要信息，关联信息等用户获取时再加载。</p>
<h3 id="延迟加载开关">延迟加载开关</h3>
<p>在mybatis核心配置文件中配置</p>
<table>
<thead>
<tr>
<th>设置项</th>
<th>描述</th>
<th>允许值</th>
<th>默认值</th>
</tr>
</thead>
<tbody>
<tr>
<td>lazyLoadingEnabled</td>
<td>全局性设置懒加载。如果设为‘false’，则所有相关联的都会被初始化加载。</td>
<td>true <!-- raw HTML omitted --> false</td>
<td>false</td>
</tr>
<tr>
<td>aggressiveLazyLoading</td>
<td>当设置为‘true’的时候，懒加载的对象可能被任何懒属性全部加载。<!-- raw HTML omitted --> 否则，每个属性都按需加载。</td>
<td>true <!-- raw HTML omitted -->  false</td>
<td>true</td>
</tr>
</tbody>
</table>
<p>例：</p>
<pre><code class="language-xml">&lt;settings&gt;
		&lt;setting name=&quot;lazyLoadingEnabled&quot; value=&quot;true&quot;/&gt;
		&lt;setting name=&quot;aggressiveLazyLoading&quot; value=&quot;false&quot;/&gt;
&lt;/settings&gt;
</code></pre>
<h3 id="一对一查询延迟加载">一对一查询延迟加载</h3>
<p>查询订单信息，关联查询用户信息。</p>
<p>默认只查询订单信息，当需要查询用户信息时再去查询用户信息。</p>
<ul>
<li>
<p>定义po类</p>
<p>在Orders类中加入User属性。</p>
</li>
<li>
<p>Mapper.xml</p>
</li>
</ul>
<pre><code>    &lt;select id=&quot;findOrdersList3&quot; resultMap=&quot;userordermap2&quot;&gt;
    	SELECT
    	orders.*
    	FROM
    	orders
    &lt;/select&gt;
</code></pre>
<ul>
<li>
<p>定义resultMap</p>
<p>看点：<code>select=&quot;findUserById&quot;</code></p>
</li>
</ul>
<pre><code>    &lt;!-- 订单信息resultmap --&gt;
    &lt;resultMap type=&quot;cn.itcast.mybatis.po.Orders&quot; id=&quot;userordermap2&quot;&gt;
        &lt;id property=&quot;id&quot; column=&quot;id&quot;/&gt;
        &lt;result property=&quot;user_id&quot; column=&quot;user_id&quot;/&gt;
        &lt;result property=&quot;number&quot; column=&quot;number&quot;/&gt;
        &lt;association property=&quot;user&quot; javaType=&quot;cn.itcast.mybatis.po.User&quot; select=&quot;findUserById&quot; column=&quot;user_id&quot;/&gt;
    &lt;/resultMap&gt;
</code></pre>
<ul>
<li>Mapper接口</li>
</ul>
<pre><code>    Public void testfindOrdersList3()throws Exception{
		//获取session
		SqlSession session = sqlSessionFactory.openSession();
		//获限mapper接口实例
		UserMapper userMapper = session.getMapper(UserMapper.class);
		//查询订单信息
		List&lt;Orders&gt; list = userMapper.findOrdersList3();
		System.out.println(list);
		//开始加载，通过orders.getUser方法进行加载
        for(Orders orders:list){
			System.out.println(orders.getUser());
		}
		//关闭session
		session.close();
	}
</code></pre>
<ul>
<li>测试</li>
</ul>
<pre><code>    Public void testfindOrdersList3()throws Exception{
		//获取session
		SqlSession session = sqlSessionFactory.openSession();
		//获限mapper接口实例
		UserMapper userMapper = session.getMapper(UserMapper.class);
		//查询订单信息
		List&lt;Orders&gt; list = userMapper.findOrdersList3();
		System.out.println(list);
		//开始加载，通过orders.getUser方法进行加载
        for(Orders orders:list){
			System.out.println(orders.getUser());
		}
		//关闭session
		session.close();
	}
</code></pre>
<ul>
<li>延迟加载的思考</li>
</ul>
<p>不使用mybatis提供的延迟加载功能是否可以实现延迟加载？</p>
<p>实现方法：</p>
<p>针对订单和用户两个表定义两个mapper方法。</p>
<p>1、订单查询mapper方法</p>
<p>2、根据用户id查询用户信息mapper方法</p>
<p>默认使用订单查询mapper方法只查询订单信息。</p>
<p>当需要关联查询用户信息时再调用根据用户id查询用户信息mapper方法查询用户信息。</p>
<h3 id="一对多延迟加载">一对多延迟加载</h3>
<p>一对多延迟加载的方法同一对一延迟加载，在collection标签中配置select内容。</p>
<h3 id="小结">小结</h3>
<ul>
<li>
<p>作用</p>
<p>当需要查询关联信息时再去数据库查询，默认不去关联查询，提高数据库性能。<strong>只有resultMap支持延迟加载</strong>设置。</p>
</li>
<li>
<p>场合</p>
<p>当只有部分记录需要关联查询其它信息时，此时可按需延迟加载，需要关联查询时再向数据库发出sql，以提高数据库性能。</p>
<p>当全部需要关联查询信息时，此时不用延迟加载，直接将关联查询信息全部返回即可，可使用resultType或resultMap完成映射。</p>
</li>
</ul>

    </div>
    <div class="article-footer">
<blockquote class="mt-2x">
  <ul class="post-copyright list-unstyled">
    <li class="post-copyright-link hidden-xs">
      <strong>Permalink: </strong>
      <a href="https://rulerLwx.gitee.io/2020/07/java-framework-mybatis-2-%E5%85%B3%E8%81%94%E6%9F%A5%E8%AF%A2/" title="Java-framework-MyBatis-2-关联查询" target="_blank" rel="external">https://rulerLwx.gitee.io/2020/07/java-framework-mybatis-2-%E5%85%B3%E8%81%94%E6%9F%A5%E8%AF%A2/</a>
    </li>
    <li class="post-copyright-license">
      <strong>License：</strong><a href="http://creativecommons.org/licenses/by/4.0/deed.zh" target="_blank" rel="external">CC BY 4.0 CN</a>
    </li>
  </ul>
</blockquote>

<div class="panel panel-default panel-badger">
  <div class="panel-body">
    <figure class="media">
      <div class="media-left">
        <a href="https://gitee.com/rulerLwx" target="_blank" class="img-burn thumb-sm visible-lg">
          <img src="https://rulerLwx.gitee.io/avatar.png" class="img-rounded w-full" alt="">
        </a>
      </div>
      <div class="media-body">
        <h3 class="media-heading"><a href="https://gitee.com/rulerLwx" target="_blank"><span class="text-dark">rulerLwx</span><small class="ml-1x">thinking...</small></a></h3>
        <div>Good Good Study, Day Day Up~</div>
      </div>
    </figure>
  </div>
</div>
    </div>
  </article>
<section id="comments">
    <div id="vcomments"></div>
</section>

</div><nav class="bar bar-footer clearfix" data-stick-bottom>
    <div class="bar-inner">
        <ul class="pager pull-left">
            <li class="prev">
                <a href="https://rulerLwx.gitee.io/2020/07/java-framework-mybatis-3-%E7%BC%93%E5%AD%98/" title="Java-framework-MyBatis-3-缓存"><i
                        class="icon icon-angle-left"
                        aria-hidden="true"></i><span>&nbsp;&nbsp;Older</span></a>
            </li>
            <li class="next">
                <a href="https://rulerLwx.gitee.io/2020/07/java-framework-mybatis-1/"
                    title="Java-framework-MyBatis-1"><span>Newer&nbsp;&nbsp;</span><i
                        class="icon icon-angle-right" aria-hidden="true"></i></a>
            </li>
            
            <li class="toggle-toc">
                <a class="toggle-btn collapsed" data-toggle="collapse" href="#collapseToc" aria-expanded="false"
                    title="Catalogue" role="button">
                    <span>[&nbsp;</span><span>Catalogue</span>
                    <i class="text-collapsed icon icon-anchor"></i>
                    <i class="text-in icon icon-close"></i>
                    <span>]</span>
                </a>
            </li>
        </ul>
        <div class="bar-right">
            <div class="share-component" data-sites="weibo,qq,wechat"
                data-mobile-sites="weibo,qq,qzone"></div>
        </div>
    </div>
</nav>

</main><footer class="footer" itemscope itemtype="http://schema.org/WPFooter">
<ul class="social-links">
    <li><a href="https://gitee.com/rulerLwx" target="_blank" title="gitee" data-toggle=tooltip data-placement=top >
            <i class="icon icon-gitee"></i></a></li>
    <li><a href="https://github.com/wolf-lea" target="_blank" title="github" data-toggle=tooltip data-placement=top >
            <i class="icon icon-github"></i></a></li>
</ul>
  <div class="copyright">
    &copy;2020  -
    2020
    <div class="publishby">
        Theme by <a href="https://github.com/xiaoheiAh" target="_blank"> xiaoheiAh </a>base on<a href="https://github.com/xiaoheiAh/hugo-theme-pure" target="_blank"> pure</a>.
    </div>
  </div>
</footer>

<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.2/MathJax.js?config=TeX-MML-AM_SVG"></script>
<script type="text/x-mathjax-config">
    MathJax.Hub.Config({
            showMathMenu: false, //disables context menu
            tex2jax: {
            inlineMath: [ ['$','$'], ['\\(','\\)'] ]
           }
    });
</script>


<script src="https://cdn.jsdelivr.net/npm/jquery@3.4.1/dist/jquery.min.js"></script>
<script>
    window.jQuery || document.write('<script src="js/jquery.min.js"><\/script>')
</script>
<script type="text/javascript" src="https://cdn.staticfile.org/highlight.js/9.15.10/highlight.min.js"></script>
<script type="text/javascript" src="https://cdn.staticfile.org/highlight.js/9.15.10/languages/python.min.js" defer></script>
<script type="text/javascript" src="https://cdn.staticfile.org/highlight.js/9.15.10/languages/javascript.min.js" defer></script><script>
    hljs.configure({
        tabReplace: '    ', 
        classPrefix: ''     
        
    })
    hljs.initHighlightingOnLoad();
</script>
<script src="https://rulerLwx.gitee.io/js/application.min.bdeb64b910570b6c41badc6a05b7afb0c8ad9efd8525de3c7257d59e786326a3.js"></script>
<script src="https://rulerLwx.gitee.io/js/plugin.min.51ff8c7317566f82259170fa36e09c4493adc9b9378b427a01ad3f017ebac7dd.js"></script>

<script>
    (function (window) {
        var INSIGHT_CONFIG = {
            TRANSLATION: {
                POSTS: 'Posts',
                PAGES: 'Pages',
                CATEGORIES: 'Categories',
                TAGS: 'Tags',
                UNTITLED: '(Untitled)',
            },
            ROOT_URL: 'https:\/\/rulerLwx.gitee.io',
            CONTENT_URL: 'https:\/\/rulerLwx.gitee.io\/searchindex.json ',
        };
        window.INSIGHT_CONFIG = INSIGHT_CONFIG;
    })(window);
</script>
<script type="text/javascript" src="https://rulerLwx.gitee.io/js/insight.min.a343cd9a5a7698336b28ef3a7c16a3a1b1d2d5fb17dc8ed04022bbe08cc5459073a15bdafa3a8a58cdd56080784bdd69fa70b1ae8597565c799c57ed00f0e120.js" defer></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tocbot/4.4.2/tocbot.min.js"></script>
<script>
    tocbot.init({
        
        tocSelector: '.js-toc',
        
        contentSelector: '.js-toc-content',
        
        headingSelector: 'h1, h2, h3',
        
        hasInnerContainers: true,
    });
</script>

<script src="https://cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/valine"></script>
<script type="text/javascript">
    var GUEST = ['nick', 'mail', 'link'];
    var meta = 'nick,mail';
    meta = meta.split(',').filter(function (item) {
        return GUEST.indexOf(item) > -1;
    });
    new Valine({
        el: '#vcomments',
        verify: null ,
        notify: null ,
        appId: 'IyAB0PSPRazTPDxitO1ddQ7O-gzGzoHsz',
        appKey: '5rBJTq4KidYF33eXwvRVhtEH',
        placeholder: 'enjoy~',
        avatar: 'mm',
        meta: meta,
        pageSize: '10' || 10,
        visitor: false 
});
</script>

  </body>
</html>
